set nocompatible
source $VIMRUNTIME/vimrc_example.vim
source $VIMRUNTIME/mswin.vim
behave mswin

set diffexpr=MyDiff()
function MyDiff()
  let opt = '-a --binary '
  if &diffopt =~ 'icase' | let opt = opt . '-i ' | endif
  if &diffopt =~ 'iwhite' | let opt = opt . '-b ' | endif
  let arg1 = v:fname_in
  if arg1 =~ ' ' | let arg1 = '"' . arg1 . '"' | endif
  let arg2 = v:fname_new
  if arg2 =~ ' ' | let arg2 = '"' . arg2 . '"' | endif
  let arg3 = v:fname_out
  if arg3 =~ ' ' | let arg3 = '"' . arg3 . '"' | endif
  let eq = ''
  if $VIMRUNTIME =~ ' '
    if &sh =~ '\<cmd'
      let cmd = '"' . $VIMRUNTIME . '\diff"'
      "let eq = '"'
    else
      let cmd = substitute($VIMRUNTIME, ' ', '" ', '') . '\diff"'
    endif
  else
    let cmd = $VIMRUNTIME . '\diff'
  endif
  silent execute '!' . cmd . ' ' . opt . arg1 . ' ' . arg2 . ' > ' . arg3 . eq
endfunction



"common start
"vundle
filetype off                   " required!

set rtp+=$VIM/vimfiles/bundle/vundle
call vundle#rc('$VIM/vimfiles/bundle')

" let Vundle manage Vundle, required
Bundle 'gmarik/vundle'
Bundle 'anzaika/go.vim'
Bundle 'aldmeris'
Bundle 'Align'
Bundle 'AndrewRadev/splitjoin.vim'
Bundle 'AutoComplPop'
Bundle 'Buffer-grep'
Bundle 'CodeOverview'
Bundle 'EasyMotion'
Bundle 'Emmet.vim'
Bundle 'file-line'
Bundle 'FuzzyFinder'
Bundle 'grep.vim'
Bundle 'gmarik/github-search.vim'
Bundle 'gmarik/hlmatch.vim'
Bundle 'gmarik/ide-popup.vim'
Bundle 'gmarik/ingretu'
Bundle 'gmarik/sudo-gui.vim'
Bundle 'gregsexton/gitv'
Bundle 'Gundo'
Bundle 'Indent-Guides'
Bundle 'jQery'
Bundle 'kien/ctrlp.vim'
Bundle 'kchmck/vim-coffee-script'
Bundle 'lastpos.vim'
Bundle 'L9'
Bundle 'Lokaltog/vim-easymotion'
Bundle 'Lokaltog/vim-powerline'
Bundle 'mark_tools'
Bundle 'matchit.zip'
Bundle 'minibufexpl.vim'
Bundle 'mkitt/Browser-refresh.vim'
Bundle 'molokai'
Bundle 'Php Doc'
Bundle 'repeat.vim'
Bundle 'rstacruz/sparkup.git'
Bundle 'surround.vim'
Bundle 'taglist.vim'
Bundle 'tComment'
Bundle 'tlib'
Bundle 'tpope/vim-fugitive'
Bundle 'tpope/vim-git'
Bundle 'tpope/vim-rails'
Bundle 'tpope/vim-unimpaired'
Bundle 'The NERD Commenter'
Bundle 'The-NERD-Tree'
Bundle 'snipMate'
Bundle 'surround.vim'
Bundle 'taglist.vim'
Bundle 'textobj-user'
"Bundle 'Vimball'
Bundle 'vimwiki'
Bundle 'Vimball'
Bundle 'ZoomWin'

filetype plugin indent on     " required!
"vundle end

let s:is_win32 = has("win32")
let s:is_gui = has("gui_running")
let mapleader = ","

if s:is_win32
"############ win32 ############

"set guifont=Courier_New:h12:cANSI
set guifont=Bitstream_Vera_Sans_Mono:h10:cANSI
let &guifontwide=iconv('幼圆:h10.5:cGB2312', 'utf-8', 'gbk')
"autocmd GUIEnter * simalt ~x  "maximize window on start

set encoding=utf-8
set termencoding=cp936
if s:is_gui
	set langmenu=zh_CN.UTF-8
	source $VIMRUNTIME/delmenu.vim
	source $VIMRUNTIME/menu.vim
endif
language messages zh_CN.UTF-8
set fileencoding=cp936  "new file default encoding
set fileformats=dos,unix,mac
"set shellxquote=\"

cunmap <C-a>
iunmap <C-y>
unmap <C-y>

else
"############ linux ############

if s:is_gui
	behave mswin
endif
set keywordprg=:help
set hlsearch incsearch

vmap <C-c> "+y
vmap <C-x> "+d
nmap <C-v> "+gP
nmap <C-a> ggVG

"you need to define these commands: ce, start

endif
"############ all platform ############

"set background=light
if s:is_gui
	colorscheme aldmeris
else
	colorscheme desert
endif
set guioptions=r
set statusline=%F%m%r%h%w\ (%{&ff},%{&fenc!=''?&fenc:&enc}%{&bomb?'+':''})%y[%l,%v][%p%%]
set laststatus=2

set fileencodings=ucs-bom,utf-8,cp936,gb18030,big5,euc-jp,euc-kr,latin1
set number
set nobackup
set tabstop=4 shiftwidth=4 smarttab autoindent smartindent
filetype indent off
autocmd FileType python,vimwiki setlocal expandtab
set confirm
"set clipboard+=unnamed
set ignorecase smartcase
"set selection=inclusive
set display=lastline
set wildmenu
set browsedir=buffer
set completeopt-=preview
set hidden
set switchbuf=useopen
set sessionoptions=folds,tabpages
set tags=./tags;
"set formatoptions+=mM "allow line break in chinese words; join chinese lines without space
"set scrolloff=3

"don't add comment symbol on new line
autocmd BufRead * set formatoptions-=r formatoptions-=o
"format
autocmd FileType javascript,xhtml,html,actionscript,mxml,xml if &fenc!='utf-8' | setlocal equalprg=js_beautify | else | setlocal equalprg=csu\ js_beautify | endif

"filetypes
autocmd BufRead *.as set filetype=actionscript
autocmd BufRead *.mxml set filetype=mxml

autocmd VimEnter * call s:Vim_Initialize()

let s:last_tab = 0
autocmd TabLeave * let s:last_tab = tabpagenr()

nnoremap <Leader>,, ,

map! <C-l> <Del>
map! <M-h> <Left>
map! <M-l> <Right>
imap <S-CR> <C-o>O
imap <Home> <C-o>^
imap ,xo <C-x><C-o>
imap ,xl <C-x><C-l>
imap ,xf <C-x><C-f>
map! ,v <C-r><C-o>"
nmap <Leader>nr :let @"=@0<CR>
nmap <Leader>nR :let @+=@"<CR>
nmap gs :up<CR>
nmap <Leader>i ^C
map <Leader>me `]
map <Leader>mb `[

smap l <Esc>i
smap h <C-o>o<Esc>i
smap c <C-o>"_c
smap d <C-o>d
smap r <C-o>y
smap s <C-o>D
smap x <C-o>"_D
smap e <C-o>Y'>
smap <silent> v <C-o>p:let @"=@0<CR>
smap w <C-o>V
smap b <Esc>p
nmap vv p
nmap VV P
"smap m <C-g><C-q>0I#<Esc>
"smap u <C-g><C-q>0o0d
"smap M <Esc>'<O/*<Esc>'>o*/<Esc>
"nmap <silent> <Leader>U ?/\*<CR>dd/\*\/<CR>dd:noh<CR>
smap <silent> m <Esc>:cal <SID>Comment()<CR>
smap <silent> u <Esc>:cal <SID>UComment()<CR>
smap <silent> M <Esc>:cal <SID>MComment(0)<CR>
smap <silent> gM <Esc>:cal <SID>MComment(1)<CR>
nmap <silent> <silent> <Leader>U :cal <SID>UMComment()<CR>
smap gm <C-g><C-q>0I
smap gu <C-g><C-q>0o0
smap gr <C-o>"+y
smap ge <C-o>"+Y
smap ga <C-g>
xmap ga <C-g>
vnoremap > >gv
vnoremap < <gv
smap t >
smap : <C-o>:
nmap <Leader>vv vlo
xmap * y/<C-r>=escape(@", '\/.*$^~[')<CR><CR>
xmap # y?<C-r>=escape(@", '\?.*$^~[')<CR><CR>
smap * <C-o>*
smap # <C-o>#
nmap <M-f> :Rgrep \<<C-r><C-w>\> *.php
nmap <M-r> :;$s/\<<C-r><C-w>\>/
vmap <M-f> y:Rgrep <C-r>=escape(@", '\.*$^~[ "')<CR> *.php
vmap <M-r> y:;$s/<C-r>=escape(@", '\/.*$^~[')<CR>/

nmap <silent> <Leader>eu :se fenc=utf-8<CR>
nmap <silent> <Leader>eg :se fenc=gbk<CR>
nmap <silent> <Leader>eb :se bomb!<CR>
nmap <silent> <C-n><C-n> :ene<CR>
nmap <silent> <C-n>n :ene<CR>:se bt=nofile bh=hide noswf<CR>
nmap <silent> <C-n><C-l> :bro e<CR>
nmap <silent> <C-n><C-u> :bro <C-r>=bufname('')==''?'w':'sav'<CR><CR>
nmap <silent> <C-n><C-k> :tabe<CR>
nmap <silent> <C-n>k :tabe<CR>:se bt=nofile bh=hide noswf<CR>
nmap <silent> <C-n><C-o> :sil !ce tc "%:p:h"<CR>
nmap <silent> <C-n><C-p> :sil !ce tc "<C-r>=getcwd()<CR>"<CR>
nmap <silent> <Leader>sc :se bt=nofile bh=hide noswf<CR>
nmap <silent> <Leader>tc :tabc<CR>
nmap <C-j> <C-w>j
nmap <C-k> <C-w>k
nmap <C-h> <C-w>h
nmap <C-l> <C-w>l
nmap <C-p> <C-w>p
nmap <M-;> <C-w>-
nmap <M-'> <C-w>+
nmap <M-,> <C-w><
nmap <M-.> <C-w>>
map <MiddleMouse> <LeftMouse><C-w>_
map <S-MiddleMouse> <LeftMouse><C-w>1_<C-w>p
imap <MiddleMouse> <LeftMouse><C-o><C-w>_
imap <S-MiddleMouse> <LeftMouse><C-o><C-w>1_<C-o><C-w>p
nmap <Leader>vX <C-w>_
nmap <Leader>vP <C-w>p<C-w>_
nmap <Leader>vx <C-w><bar>
nmap <Leader>vp <C-w>p<C-w><bar>
nmap <silent> <Leader>l :b#<CR>`"
nmap <silent> gl :cal <SID>GotoLastTab()<CR>
map <silent> <C-MiddleMouse> <LeftMouse>:q<CR>
imap <silent> <C-MiddleMouse> <LeftMouse><C-o>:q<CR>
nmap <silent> <Leader>q :q<CR>
nmap <silent> <Leader>x :x<CR>
nmap <silent> <Leader>gq :b#<CR>:bd!#<CR>
nmap <silent> <Leader>gx :up<CR>:b#<CR>:bd#<CR>
nmap <silent> <Leader>cm :windo difft<CR>

nmap <silent> <F3> :noh<CR>
nmap <silent> <Leader>so :sy sync fromstart<CR>
nmap <Leader>p :cd %:h<CR>:pwd<CR>
"nmap <Leader>P :windo cd <C-r>=expand('%:p:h')<CR><CR>
nmap <Leader>P :let @"=expand('%:p:h')<CR><C-w>p:cd <C-r>"<CR>
nmap <silent> <F11> :Shell!<CR>
nmap <Leader>sh :Shell 
nmap <Leader>ss :SilSh 
nmap <silent> gf :cal <SID>Browser('')<CR>
vmap <silent> gf y:cal <SID>Browser(@")<CR>
nmap <silent> <Leader>gf :up<CR>:cal <SID>BrowseFile()<CR>
nmap <Leader>/ /\<\><Left><Left>
nmap <Leader>? ?\<\><Left><Left>
"Remove the Windows ^M
nmap <silent> <Leader>mr :%s/\r//g<CR>:se ff=dos<CR>:noh<CR>''
"Remove tailing whitespace
nmap <silent> <Leader>ta :%s/\s\+$<CR>:noh<CR>''
nmap <F6> :redi @+><CR>
nmap <S-F6> :redi END<CR>
imap <F6> <C-o>:redi @+><CR>
imap <S-F6> <C-o>:redi END<CR>
nmap <Leader>mp ^y$:<C-r>"<CR>
nmap <C-LeftMouse> <LeftMouse>g<C-]>

"fix
nmap Y y$
nmap <M-v> :pu!+<CR>
"imap <C-v> <C-r><C-o>+
"vnoremap <C-v> c<C-r><C-o>+
nnoremap <Leader>a <C-a>


"Plugin
"netrw
"the default curl sometimes has problems on fetching web
let g:netrw_http_cmd = 'wget -nv -U "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17" -O'

"NERDTree
let NERDTreeQuitOnOpen = 1
nmap <silent> <Leader>nl :NERDTreeToggle<CR>
nmap <silent> <Leader>nn :NERDTree %:p:h<CR>
nmap <silent> <Leader>np :NERDTree<CR>
"nmap <silent> <Leader>nn :NERDTreeFind<CR>
"command <go> instead
nmap <Leader>mf :let NERDTreeQuitOnOpen=NERDTreeQuitOnOpen?0:1<CR>:ec NERDTreeQuitOnOpen<CR>

"TagList
let Tlist_Use_Right_Window = 1
let Tlist_Exit_OnlyWindow = 1
let tlist_actionscript_settings = 'actionscript;c:class;i:interface;f:method;p:property;v:variable'
let tlist_mxml_settings = 'actionscript;f:method;p:property;v:variable'
nmap <silent> <Leader>tl :TlistToggle<CR>

"acp
let g:acp_behaviorKeywordCommand = "\<C-p>"
"let g:acp_behaviorKeywordLength = 3
"let g:acp_completeOption = ".,w,b,u,t,i"
"let g:acp_mappingDriven = 1
"fix tag close in xml
autocmd FileType xml,mxml imap <buffer> / /<Esc>a

"FuzzyFinder
let g:fuf_modesDisable = [ 'mrucmd' ]
nmap <silent> <Leader>fb :FufBuffer<CR>
nmap <silent> <Leader>fo :FufFile<CR>
"nmap <silent> <Leader>O :FufFile **/<CR>
nmap <silent> <Leader>fc :FufCoverageFile<CR>
nmap <silent> <Leader>d :FufFileWithCurrentBufferDir<CR>
nmap <silent> <Leader>r :FufMruFile<CR>
nmap <silent> <Leader>hp :FufDir<CR>
nmap <silent> <Leader>hd :FufDirWithCurrentBufferDir<CR>
nmap <silent> <Leader>ff :FufBookmarkFile<CR>
nmap <silent> <Leader>hh :FufBookmarkDir<CR>
nmap <silent> <Leader>jf :FufBufferTag<CR>
nmap <silent> <Leader>jb :FufBufferTagAll<CR>
nmap <silent> <Leader>jt :FufTag<CR>
"as support
let g:fuf_buffertag__actionscript = '--language-force=actionscript --actionscript-types=cifpv'
let g:fuf_buffertag__mxml = '--language-force=actionscript --actionscript-types=fpv'
"fuf commands
function s:GetAllCommands()
  redir => commands
  silent command
  redir END
  return map((split(commands, "\n")[1:]),
	  \      '":" . matchstr(v:val, ''^....\zs\S*'')')
endfunction
" execute one of the user-defined commands 
nmap <silent> <S-F4> :cal fuf#givencmd#launch('', 0, '>', <SID>GetAllCommands())<CR>
nmap <silent> <F4> :cal fuf#givencmd#launch(':Fuf', 0, '>', <SID>GetAllCommands())<CR>
"fuf windows
function s:GetWins()
	let output = system('getwin -l')
	return split(iconv(output, 'gbk', 'utf-8'), "\n")
endfunction
let fuf_getwin = {}
function fuf_getwin.onComplete(item, method)
	let hwnd = split(a:item, '\.')[0]
	"silent! execute '!getwin -s '.hwnd
	call system('getwin -s '.hwnd)
endfunction
nmap <silent> <Leader>gw :cal fuf#callbackitem#launch('', 0, 'win>', fuf_getwin, <SID>GetWins(), 0)<CR>
"fuf marks
function s:GetMarks()
  redir => marks
  silent marks
  redir END
  return filter(split(marks, "\n")[1:], 'v:val !~ ''^ \d''')
endfunction
let fuf_getmark = {}
function fuf_getmark.onComplete(item, method)
	let m = split(a:item)[0]
	execute "normal '".m
endfunction
nmap <silent> <Leader>jm :cal fuf#callbackitem#launch('', 0, 'mark>', fuf_getmark, <SID>GetMarks(), 0)<CR>

"grep
if s:is_win32
	let Grep_Find_Path = 'find1'
	let Grep_Xargs_Path = 'xargs1'
	let Fgrep_Path = 'grep -F'
	let Egrep_Path = 'grep -E'
	let Grep_Shell_Quote_Char = '"'
endif
let Grep_Skip_Dirs = '.svn .git'
let Grep_Skip_Files = '*~ *.swp *.pyc'
"toggle search gbk & utf-8 file
nmap <Leader>gg :let [Grep_Path,Fgrep_Path,Egrep_Path]=['cei grep','cei grep -F','cei grep -E']<CR>:ec 'grep for gbk'<CR>
nmap <Leader>gu :let [Grep_Path,Fgrep_Path,Egrep_Path]=['grep','grep -F','grep -E']<CR>:ec 'grep for utf-8'<CR>

"emmet
let g:user_emmet_mode='iv'

"surround
smap S <C-o>S

"textobj-user
"if exists('*textobj#user#plugin')
	call textobj#user#plugin('my', {
		\ 'comment': {
		\ 	'*pattern*': ['/\*', '\*/'],
		\ 	'select-a': 'am',
		\ 	'select-i': 'im',
		\ },
		\ 'comment_html': {
		\ 	'*pattern*': ['<!--', '-->'],
		\ 	'select-a': 'aM',
		\ 	'select-i': 'iM',
		\ },
		\ 'cdata': {
		\ 	'*pattern*': ['<!\[CDATA\[', '\]\]>'],
		\ 	'select-a': 'aC',
		\ 	'select-i': 'iC',
		\ },
		\ 'indent_a': {
		\ 	'*select-function*': 'SelectIndentA',
		\ 	'select': ['ai'],
		\ },
		\ 'indent_i': {
		\ 	'*select-function*': 'SelectIndentI',
		\ 	'select': ['ii'],
		\ },
	\ })
"endif

function SelectIndentA()
	return s:SelectIndent('a')
endfunction

function SelectIndentI()
	return s:SelectIndent('i')
endfunction

function s:SelectIndent(mode)
	let indent = matchstr(getline("."), '^\s*')
	if indent == ''
		return ['V', [0,1,1,0], [0,line('$'),1,0]]
	endif
	let cpos = getpos('.')
	let c = strlen(indent)
	let headno = search('^\s\{0,'.(c-1).'}\S', 'bW')
	if headno != 0 && a:mode == 'i'
		+1
	endif
	let head = getpos('.')
	let tailno = search('^\s\{0,'.(c-1).'}\S', 'W')
	let is_brace = 0
	if tailno != 0
		if getline('.') =~ '^\s*\([]})]\|end\)'
			let is_brace = 1
		endif
		if a:mode == 'i' || !is_brace
			-1
		endif
	endif
	"skip the end blank lines
	if a:mode == 'i' && !is_brace
		while line('.') > 1 && getline('.') =~ '^\s*$'
			-1
		endwhile
	endif
	let tail = getpos('.')
	call setpos('.', cpos)
	return ['V', head, tail]
endfunction

"vimwiki
autocmd FileType vimwiki nmap <leader>tt <Plug>VimwikiToggleListItem

"initialize
function s:Vim_Initialize()
	"codes below will run after plugins all ready
	set vb t_vb=
endfunction

function s:GotoLastTab()
	if s:last_tab
		execute 'tabn ' . s:last_tab
	endif
endfunction

"phpcomplete(not search in tags)
function MyCompletePHP(findstart, base)
	let t=&tags
	set tags=
	let result = phpcomplete#CompletePHP(a:findstart, a:base)
	let &tags=t
	return result
endfunction
autocmd FileType php set omnifunc=MyCompletePHP

"Embed Shell Command
let s:_ = ''
function s:ExecuteInShell(command, bang)
	if a:bang != ''
		let _ = s:_
	elseif a:command == ''
		let _ = ''
	else
		let _ = substitute(a:command, '\c[%#]\%(:\w\)*\|<cword>\|<cfile>', '\=shellescape(expand(submatch(0)))', 'g')
	endif
	if _ == '' | return | endif

	let s:_ = _
	let fname = fnameescape(_)
	let winnr = bufwinnr('^' . fname . '$')
	if winnr < 0
		silent! execute 'keepalt botright new ' . fname
		setlocal buftype=nofile bufhidden=hide noswapfile nobuflisted number
		"execute 'resize ' . line('$')
		resize 10
		execute "nmap <silent> <buffer> <CR> :cal <SID>ExecuteInShell('" . _ . "', '')<CR>"
		nmap <silent> <buffer> q :q<CR>
	else
		execute winnr . 'wincmd w'
		%delete
	endif
	let message = 'Execute ' . _ . '...'
	echo message
	silent! execute '%!ce '. _
endfunction
command -complete=shellcmd -nargs=? -bang Shell call s:ExecuteInShell(<q-args>, '<bang>')

"Silent Shell Command (for multi-threading)
function s:SilentShell(command)
	silent execute '!start cmd /c "ce '.a:command.' & pause"'
endfunction
command -nargs=1 SilSh call s:SilentShell(<q-args>)

function s:Fixpath(path)
	return substitute(a:path, '\', '/', 'g')
endfunction

"quickfixdo
command! -nargs=0 -bar Qargs execute 'args ' . s:QuickfixFilenames()
command! -nargs=1 Qfdo call s:QuickfixDo(<q-args>)
function! s:QuickfixFilenames()
  " Building a hash ensures we get each buffer only once
  let buffer_numbers = {}
  for quickfix_item in getqflist()
    let buffer_numbers[quickfix_item['bufnr']] = bufname(quickfix_item['bufnr'])
  endfor
  return join(values(buffer_numbers))
endfunction
function s:QuickfixDo(cmd)
	Qargs
	execute 'argdo '.a:cmd
endfunction

"Run
function s:Run(cmd)
	if a:cmd != ''
		let cmd = a:cmd
	else
		let cmd = get(s:runprgs, &ft, '')
		if cmd == '' | return | endif
	endif
	silent update
	lcd %:h
	execute 'Shell '.cmd.' %'
endfunction

"browse url in current line
function s:Browser(url)
	if a:url == ""
		let line0 = expand('<cWORD>')
		"let line0 = getline(".")
	else
		let line0 = a:url
	endif
	if line0 != ""
		let line = matchstr(line0, '\(https\?\|ftp\|file\)://[^,;"''>]*')
		if line != ""
			silent execute '!ce start "" '.shellescape(line, 1)
			return
		endif
	endif
	if a:url == ""
		normal! gf
	else
		normal! gvgf
	endif
endfunction

let s:webroot = {}
"browse current file
function s:BrowseFile()
	let line = s:Fixpath(expand('%:p'))
	let isweb = 0
	if len(s:webroot)
		for [host, path] in items(s:webroot)
			let pat = '^\c\V'.path.'/'
			if line =~ pat
				let line = substitute(line, pat, 'http://'.host.'/', '')
				let isweb = 1
				break
			endif
		endfor
	endif
	if !isweb
		let line = 'file:///'.line
	endif
	silent execute '!ce start "" '.shellescape(line)
endfunction

function s:CloseHiddenBuffers()
  let open_buffers = []

  for i in range(1, tabpagenr('$'))
    call extend(open_buffers, tabpagebuflist(i))
  endfor
  "bufdo let num = bufnr('%') | if index(open_buffers, num) == -1 && &modified | call add(open_buffers, num) | endif

  for i in range(1, bufnr("$"))
    if buflisted(i) && index(open_buffers, i) == -1
      execute "bdelete ".i
    endif
  endfor
endfunction
command CloseHiddenBuffers call s:CloseHiddenBuffers()

"comments
let s:sl_cmts = {
	\ '//': 'php,javascript,xhtml,html,mxml,actionscript',
	\ '"': 'vim',
	\ '::': 'dosbatch',
\}
let s:ml_cmts = [
	\ ["'''", "'''", 'python'],
	\ ['<!--', '-->', 'xhtml,html,xml'],
\]
function s:GetSlCmt()
	let c = '#'
	for [sym, ftypes] in items(s:sl_cmts)
		if ftypes =~ '\<'.&filetype.'\>'
			let c = sym
			break
		endif
	endfor
	return c
endfunction
function s:GetMlCmt()
	let c = ['/*', '*/']
	for syms in s:ml_cmts
		if syms[2] =~ '\<'.&filetype.'\>'
			let c = syms[:1]
			break
		endif
	endfor
	return c
endfunction
function s:Comment()
	let c = s:GetSlCmt()
	execute "'<,'>substitute/^/".escape(c, '\/')
endfunction
function s:UComment()
	let c = s:GetSlCmt()
	execute "'<,'>substitute/^.\\{".strlen(c)."}"
endfunction
function s:MComment(forjs)
	if !a:forjs
		let [c1, c2] = s:GetMlCmt()
	else
		let [c1, c2] = ['/*', '*/']
	endif
	let indent = matchstr(getline("'<"), '^\s*')
	call append(line("'<")-1, indent.c1)
	call append("'>", indent.c2)
endfunction
function s:UMComment()
	let [c1, c2] = s:GetMlCmt()
	execute '?\V'.escape(c1, '\?').'?delete'
	execute '/\V'.escape(c2, '\/').'/delete'
endfunction

"templates
let s:tpl_exts = {'html':'html', 'jqm':'html', 'html5':'html'}
function s:NewTemplate(ftype, bang)
	let tpl = $VIM.'/vimfiles/template/'.a:ftype.'.'.s:tpl_exts[a:ftype]
	if a:bang == ''
		silent execute 'edit '.tpl
		keepalt 0file
	else
		silent execute 'read '.tpl
	endif
endfunction
command -nargs=1 -bang New call s:NewTemplate(<q-args>, '<bang>')

let s:proroot = ''
function s:GetProDir()
	return s:proroot == '' ? '' : matchstr(s:Fixpath(expand('%:p:h')), '^\c\V'.s:proroot.'\m/[^/]\+')
endfunction
function s:SvnPro(type)
	let path = s:GetProDir()
	if path == ""
		echo 'Not in project dir'
		return
	endif
	wall
	if a:type == 'ci'
		execute 'SilSh svn ci -m "" '.shellescape(path)
	elseif a:type == 'up'
		execute 'SilSh svn up --accept=postpone '.shellescape(path)
	endif
endfunction

let s:stxs = []
function s:StxMap(type)
	let f = expand('%:p')
	for [src, dest] in s:stxs
		if src ==? f
			let cp = s:is_win32 ? 'ce copy /y' : 'cp'
			if a:type == 'ci'
				silent execute '!'.cp.' "%" '.shellescape(dest)
			else
				silent execute '!'.cp.' '.shellescape(dest).' "%"'
			endif
			break
		endif
	endfor
endfunction

function s:Rename(fname)
	execute 'saveas '.a:fname
	let oldf = expand('#:p')
	bdelete #
	call delete(oldf)
endfunction
command -nargs=1 Ren call s:Rename(<q-args>)

"for scratch saveas
function s:SaveAs(fname)
	execute 'write '.a:fname
	execute 'edit '.a:fname
endfunction
command -nargs=1 Sv call s:SaveAs(<q-args>)

function s:EditClipBrd(bang)
	setlocal buftype=nofile bufhidden=hide noswapfile
	normal "+p
	if getline(1) == '' | 1d | endif
	if a:bang == ''
		autocmd BufUnload <buffer> normal ggVG"+y
	endif
endfunction
command -bang ClipBrd call s:EditClipBrd('<bang>')

function s:ViewHtml()
	silent! execute 'Nread '.@+
	set noreadonly
	setlocal buftype=nofile bufhidden=hide noswapfile
	set filetype=html
	if getline(1) == '' | 1d | endif
	execute 'file '.fnameescape(@+)
endfunction
command ViewHtml call s:ViewHtml()

let s:flexroot = ''
function s:GetFlexDir()
	return s:flexroot == '' ? '' : matchstr(s:Fixpath(expand('%:p:h')), '^\c\V'.s:flexroot.'\m/[^/]\+')
endfunction
function s:FlexMake(type)
	let path = s:GetFlexDir()
	if path == "" | return | endif
	update
	execute "lcd ".path
	if a:type == 1
		SilSh ant
	else
		SilSh ant -f build-r.xml
	endif
endfunction


"shell command
let s:runprgs = {'python':'py3', 'php':'php', 'javascript':'cscript //nologo'}
nmap <silent> <Leader>1 :up<CR>:lc %:h<CR>:sil make "%"<CR>:cope<CR>
nmap <silent> <Leader><Space> :cal <SID>Run('')<CR>
autocmd FileType python nmap <silent> <buffer> <Leader>2 :cal <SID>Run('python')<CR>
autocmd FileType php setlocal makeprg=php\ -l errorformat=%m\ in\ %f\ on\ line\ %l
autocmd FileType mxml,actionscript nmap <silent> <buffer> <Leader>1 :cal <SID>FlexMake(1)<CR>
	\ | nmap <silent> <buffer> <Leader>2 :cal <SID>FlexMake(2)<CR>

nmap <silent> <Leader>cf :up<CR>:SilSh svn ci -m "" "%"<CR>
nmap <silent> <Leader>cd :wa<CR>:SilSh svn ci -m "" "%:h"<CR>
nmap <silent> <Leader>cD :wa<CR>:sil !ce start TortoiseProc /command:commit /path:"%:h"<CR>
nmap <silent> <Leader>cp :wa<CR>:SilSh svn ci -m ""<CR>
nmap <silent> <Leader>cP :wa<CR>:sil !ce start TortoiseProc /command:commit /path:"<C-r>=getcwd()<CR>"<CR>
nmap <silent> <Leader>uf :up<CR>:SilSh svn up --accept=postpone "%"<CR>
nmap <silent> <Leader>ud :wa<CR>:SilSh svn up --accept=postpone "%:h"<CR>
nmap <silent> <Leader>up :wa<CR>:SilSh svn up --accept=postpone<CR>
nmap <silent> <Leader>cj :cal <SID>SvnPro('ci')<CR>
nmap <silent> <Leader>cJ :wa<CR>:sil !ce start TortoiseProc /command:commit /path:"<C-r>=<SID>GetProDir()<CR>"<CR>
nmap <silent> <Leader>uj :cal <SID>SvnPro('up')<CR>
nmap <silent> <Leader>sa :SilSh svn add "%:p"<CR>
nmap <silent> <Leader>sr :SilSh svn resolve --accept=working "%"<CR>
nmap <silent> <Leader>cg :cal <SID>StxMap('ci')<CR>
nmap <silent> <Leader>ug :cal <SID>StxMap('up')<CR>

nmap <silent> <Leader>gp :let @+=expand('%:p')<CR>
nmap <silent> <Leader>ep :sil !ce editplus -cursor <C-r>=line('.')<CR>:1 "%:p"<CR>
nmap <Leader>mv :cd ~<CR>:mks!<CR>
nmap <Leader>sv :so ~/Session.vim<CR>
nmap <silent> <Leader>sd :sil !ce start cmd /k cd /d "%:h"<CR>
nmap <silent> <Leader>sp :sil !start cmd<CR>

nmap <Leader>hv :cd $VIM/vimfiles<CR>
nmap <silent> <Leader>nv :NERDTree $VIM/vimfiles<CR>
nmap <Leader>hj :cd <C-r>=<SID>GetProDir()<CR><CR>:pwd<CR>
nmap <silent> <Leader>nj :NERDTree <C-r>=<SID>GetProDir()<CR><CR>

"set filetype
nmap <silent> <Leader>tp :se ft=php<CR>
nmap <silent> <Leader>th :se ft=html<CR>
nmap <silent> <Leader>tj :se ft=javascript<CR>
nmap <silent> <Leader>ts :se ft=css<CR>
nmap <silent> <Leader>ty :se ft=python<CR>
"common end

nmap <silent> <Leader>cs1 :wa<CR>:SilSh svn ci -m "" G:\work\stab\jibo_stu<CR>
nmap <silent> <Leader>us1 :wa<CR>:SilSh svn up --accept=postpone G:\work\stab\jibo_stu<CR>
nmap <silent> <Leader>cs2 :wa<CR>:SilSh svn ci -m "" G:\work\stab\lms<CR>
nmap <silent> <Leader>us2 :wa<CR>:SilSh svn up --accept=postpone G:\work\stab\lms<CR>
nmap <Leader>hc :cd D:\home\root\MyDoc\文档\笔记<CR>
nmap <silent> <Leader>ur :sil !py3 D:\bin\py\vimrc.py up<CR>
nmap <silent> <Leader>cr :sil !py3 D:\bin\py\vimrc.py ci<CR>
nmap <Leader>hq :cd G:\work\qeephp\library<CR>
nmap <Leader>hw :cd G:\work<CR>
nmap <silent> <Leader>nw :NERDTree G:\work<CR>

nmap <silent> <Leader>cc :wa<CR>:SilSh svn ci -m "" "D:\home\root\MyDoc\文档\笔记"<CR>
nmap <silent> <Leader>uc :wa<CR>:SilSh svn up "D:\home\root\MyDoc\文档\笔记"<CR>
nmap <silent> <Leader>nc :NERDTree D:\home\root\MyDoc\文档\笔记<CR>

let s:webroot = {'localhost':'G:/www', 'work.myweb':'G:/work'}
let s:proroot = 'G:/work'
let s:flexroot = 'G:/flex'
let s:chrome_dir = 'C:\Users\Admin\AppData\Local\Google\Chrome\User Data\Default\Extensions'
let s:stx_dir = 'd:\etc'
let s:stxs = [
	\[s:chrome_dir.'\dbepggeogbaibhgnhhndojpepiihcmeb\1.44_0\background_scripts\custom.js', s:stx_dir.'\custom_v.js'],
	\[s:chrome_dir.'\jlgkpaicikihijadgifklkbpdajbkhjo\2.7.6_1\js\custom.js', s:stx_dir.'\custom_g.js'],
	\['d:\bin\py\zkrun.py', s:stx_dir.'\zkrun.py'],
\]
set directory=.,$TEMP
let g:vimwiki_list = [{'path': 'd:\home\root\MyDoc\vimwiki'}]
